<?php

namespace admin\controllers;

use Yii;
use yii\bootstrap\Html;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\web\Controller;

/**
 * Ajax Controller
 */
class AjaxController extends Controller
{
    private $return = [
        'error' => 1,
        'msg' => '系统错误！',
    ];

    public function actionSelect($model, $attribute, $exclude)
    {
        $select = '';
        $parent_id = Yii::$app->request->post('parent_id');

        if($parent_id){
            $inputName = Html::getInputName(new $model, $attribute);
            $datas = $model::getSelectDatas($parent_id, $exclude);
            if($datas){
                $select = Html::dropDownList($inputName, '', $datas, [
                    'class' => 'form-control form-control-inline',
                    'ajax-select' => Url::to(['ajax/select', 'model' => $model, 'attribute' => $attribute, 'parent_id' => $parent_id]),
                ]);
            }
        }

        return $this->success(['html' => $select]);
    }

    private function error($params)
    {
        $return = array_merge($this->return, $params);
        $return['error'] = 1;
        return Json::encode($return);
    }

    private function success($params)
    {
        $return = array_merge($this->return, $params);
        $return['error'] = 0;
        return Json::encode($return);
    }
}
